package com.hbu.product.hbumallproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbu.common.utils.PageUtils;
import com.hbu.common.utils.Query;
import com.hbu.product.hbumallproduct.dao.SkuInfoDao;
import com.hbu.product.hbumallproduct.entity.SkuInfoEntity;
import com.hbu.product.hbumallproduct.service.SkuInfoService;
import com.hbu.product.hbumallproduct.vo.SkuInfoListVO;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Map;


/**
 * @author 90458
 */
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils getSkuList(SkuInfoListVO skuInfoList) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = skuInfoList.getKey();
        if (StringUtils.hasText(key)) {
            queryWrapper.and(row -> row.eq("sku_id", key).or().like("sku_name", key));
        }
        Long brandId = skuInfoList.getBrandId();
        if (null != brandId && brandId != 0) {
            queryWrapper.eq("brand_id", brandId);
        }
        BigDecimal min = skuInfoList.getMin();
        BigDecimal max = skuInfoList.getMax();
        if (null != min && min.compareTo(BigDecimal.ZERO) > 0) {
            queryWrapper.ge(Boolean.TRUE, "price", min);
        }
        
        if (null != max && max.compareTo(BigDecimal.ZERO) > 0) {
            // 还要保证 max 大于 min
            if (null != min) {
                if (max.compareTo(min) > 0) {
                    queryWrapper.le(Boolean.TRUE, "price", max);
                }
            } else {
                queryWrapper.le(Boolean.TRUE, "price", max);
            }
        }
        Long catelogId = skuInfoList.getCatelogId();
        if (null != catelogId && catelogId != 0) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        return new PageUtils(this.page(new Page<>(skuInfoList.getPageOrDefault(), skuInfoList.getLimitOrDefault()), queryWrapper));
    }

    @Override
    public String getNameById(Long skuId) {
        return baseMapper.getNameById(skuId);
    }
}